import { Bi } from "@/module-00-codebase/pkg-01-container";
import { Throwable } from "@/module-00-codebase/pkg-02-tool";
import { RpcResult } from "@/module-00-codebase/pkg-08-entity/rpc-result";

export class Sign {
  public async in(username: string, password: string) {
    let res: RpcResult | undefined;
    let _username: string, _password: string;
    if (username === "token") {
      res = new RpcResult(true, { data: { id: password, username: "token", password: "" } });
      _username = "token";
      _password = "";
    } else {
      res = await Bi.rpc.send({ resourceName: "innerToken", action: "post", data: { username, password } });
      _username = username;
      _password = password;
    }
    if (res?.result === true) {
      Bi.cacheManager.write("token", res.data.data.id);
      Bi.cacheManager.write("account", { username: _username, password: _password });
      await Bi.permManager.refresh();
    } else {
      Throwable(res?.message || "Unknown Error.");
    }
    return res;
  }
  public async out() {
    Bi.cacheManager.clear();
    await Bi.permManager.refresh();
  }
  public async up(username: string, password: string) {
    const res = await Bi.rpc.send({ action: "post", resourceName: "innerToken", data: { username, password } });
    Bi.cacheManager.write("token", res.data.token);
  }
}
export const dependencies = () => ["CacheManager"];
